// @Description
// @Author  xiaoyang
// @Date  2022/2/27 4:32 下午

package main

import (
	"fmt"
	golang_rpc "golang-rpc"
	"log"
	"net"
	"sync"
	"time"
)

func main() {
	addr := make(chan string)
	go startServer(addr)

	// 创建client端口
	client, err := golang_rpc.Dial("tcp", <-addr)
	if err != nil {
		log.Fatal("[client] client create error")
		return
	}
	defer func() { _ = client.Close() }()

	time.Sleep(time.Second)

	// 并发推送方法和参数，server端实例化，返回结果集
	var wg sync.WaitGroup
	for i := 0; i < 5; i++ {
		wg.Add(1)
		go func(i int) {
			defer wg.Done()
			args := fmt.Sprintf("[client] request args %d", i)
			var reply string
			if err := client.Call("Test.Sum", args, &reply); err != nil {
				log.Fatal("[client] client response error : " + err.Error())
			}
			log.Println("[client] response reply is :", reply)
		}(i)
	}
	wg.Wait()
}

/**
 *  @Author yang
 *  @Description 开启服务端监听
**/
func startServer(addr chan string) {
	lis, err := net.Listen("tcp", ":0")
	if err != nil {
		log.Fatal("network error :", err)
	}
	log.Println("start rpc server on :", lis.Addr().String())
	addr <- lis.Addr().String()
	golang_rpc.Accept(lis)
}
